package com.tjakus.quartz;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import com.tjakus.hibernate.HibernateUtil;
import com.tjakus.hibernate.Statistics;
import com.tjakus.hibernate.Users;
import com.tjakus.logging.Logging;

/**
 * This class represents quartz job which is responsible for updating statistics
 * in database.
 * 
 * @author tjakus
 * 
 */

public class JobUpdateStatistics implements Job {

	/**
	 * This method executes quartz job which is responsible for updating
	 * statistics in database.
	 * 
	 */
	public void execute(JobExecutionContext context) throws JobExecutionException {
		Logging.getLogger().info("JobUpdateStatistics - execute - [ STARTED ]");
		// Get all users from database
		List<Users> users = HibernateUtil.getAllUsers();
		if (users == null) {
			Logging.getLogger().error(
					"JobUpdateStatistics - execute - [ ERROR GETTING USERS ]");
			return;
		}
		// For all users do
		for (Iterator<Users> iter = users.iterator(); iter.hasNext();) {
			Users user = iter.next();
			Statistics oldStatistic;
			// Get latest statistic from database 
			oldStatistic = HibernateUtil.getLatestStatisticsByEmail(user.getEmail());
			if (oldStatistic == null) {
				Logging.getLogger().error(
						"JobUpdateStatistics - execute - [ UNABEL TO GET STATISTIC or NO STATICTISC FOR THIS USER]");
				// If there is no records in statistic table for this user,
				// add it for first time
				this.addNewStatistic(user, 0);
			} else {
				// latest statistic from database found
				// Add new record with calculated mail counter per day
				Logging.getLogger().debug(
						"JobUpdateStatistics - oldStatistic - [ " + oldStatistic.getEmail() + " "
								+ oldStatistic.getMailCounter() + " ]");
				this.addNewStatistic(user, oldStatistic.getMailCounter());
			}
		}
		Logging.getLogger().info("JobUpdateStatistics - execute - [ FINISHED ]");
	}

	/**
	 * This method adds new statistics record in database
	 * 
	 */
	private void addNewStatistic(Users user, int oldStatisticMailCounter) {
		Date utilDate = new Date();
		java.sql.Date today = new java.sql.Date(utilDate.getTime());
		Statistics newStatistic = new Statistics();
		newStatistic.setEmail(user.getEmail());
		newStatistic.setMailCounter(user.getMailCounter());
		newStatistic.setDate(today);
		newStatistic.setMailCounterPerDay(user.getMailCounter()
				- oldStatisticMailCounter);
		HibernateUtil.addStatistic(newStatistic);
		Logging.getLogger().info(
				"JobUpdateStatistics - addNewStatistic - [ " + newStatistic.getEmail()
						+ ": " + newStatistic.getMailCounterPerDay() + " ]");
	}
}
